from datetime import datetime

from pydantic import BaseModel
from sqlalchemy import Column, Integer, String, select, DateTime
from sqlalchemy.orm import declarative_base

from utils.drivers.database.engine import AsyncSession
from utils.enums import Language
from utils.exception import AppException, StatusCode

Base = declarative_base()

class NewsTypeModel(BaseModel):
    id: int
    name: str
    sort: int
    create_time: datetime
    update_time: datetime

class NewsType(Base):
    __tablename__ = "news_type"

    id = Column(Integer, primary_key=True, autoincrement=True)
    key = Column(String(255))
    name = Column(String(255))
    sort = Column(Integer)
    create_time = Column(DateTime, default=datetime.now())
    update_time = Column(DateTime, default=datetime.now(), onupdate=datetime.now())

    def model(self, language: Language) -> NewsTypeModel:
        return NewsTypeModel(
            id=self.id, # type: ignore
            name= self.name if language == Language.CN else self.key,  # type: ignore
            sort=self.sort,  # type: ignore
            create_time=self.create_time,  # type: ignore
            update_time=self.update_time,  # type: ignore
        )

    @classmethod
    async def get_all(cls) -> list["NewsType"]:
        try:
            async with AsyncSession() as session:
                async with session.begin():
                    news_type_list = await session.execute(select(cls).order_by(cls.sort.asc()))
                    news_type_list = news_type_list.scalars().all()
                    if not news_type_list:
                        news_type_list = []
        except Exception as e:
            raise AppException(StatusCode.QueryAllNewsTypeError, detail=str(e))

        return news_type_list
